<?php
/**
 * 优惠券相应控制器
 * CouponModel.class.php
 *
 * @author 	王中艺
 * @date  	2017-02-06
 */

namespace Wechat\Model;

class CouponModel extends BaseModel {
    
    //重定义数据表
	protected   $trueTableName = 't_coupon_code';

    /**
     * 使用优惠码
     * @param   $code 优惠码
     * @param   $userId 用户ID
     * @param   $amount 消费金额
     * @param   $stopTrans 是否停止事物
     * @return  $codeInfo 	优惠码信息
     */
    function useCouponCode($code, $userId, $amount = false, $stopTrans = false){
    	$codeInfo 	= $this->checkCouponCode($code, $userId, $amount);
        if($codeInfo === false) 
            return false;

        $stopTrans or $this->startTrans();

        $codeInfo['use_count']  += 1;
        $result     = $this->where('id = %d', $codeInfo['id'])->setInc('use_count');
        if($result === false){
            $stopTrans or $this->rollback();
            $this->errMsg   = '数据更新失败!(t_coupon_code)';
            return false;
        }

        $useInfo    = array(
            'user_id' => $userId,
            'code_id'   => $codeInfo['id'],
            'use_time'  => time()
        );
        $result     = M('t_coupon_code_use', null)->add($useInfo);
        if($result === false){
            $stopTrans or $this->rollback();
            $this->errMsg   = '数据更新失败!(t_coupon_code_use)';
            return false;
        }

        $stopTrans or $this->commit();

    	return $codeInfo;
    }

    /**
     * 检测优惠吗
     * @param   $code 优惠码
     * @param   $userId 用户ID
     * @param   $amount 花费金额
     * @return  $couponInfo 优惠码信息
     */
    function checkCouponCode($code, $userId, $amount = false){
        $codeInfo = $this->where('id = %d or code = "%s"', $code, $code)->cache(true)->find();
        if(!$codeInfo){
            $this->errMsg   = '无效优惠码!';
            return false;
        }
        if($codeInfo['status'] != 1){
            $this->errMsg   = '该优惠码已被禁用!';
            return false;
        }
        if($codeInfo['end_time'] < time()){
            $this->errMsg   = '该优惠码已过期!';
            return false;
        }
        
        $isUse  = M('t_coupon_code_use', null)
            ->where('user_id = %d and code_id = %d', $userId, $codeInfo['id'])
            ->find();
        if($isUse){
            $this->errMsg   = '您已使用过该优惠码!';
            return false;
        }
        if($amount !== false && $amount < $codeInfo['limit_amount']){
            $this->errMsg   = '未达到指定金额!';
            return false;
        }
        return $codeInfo;
    }
}